package com.haohan.cloud.scm.opc.api.ctrl;

import com.haohan.cloud.scm.api.opc.dto.SettlementRecordDTO;
import com.haohan.cloud.scm.api.opc.entity.SettlementRecord;
import com.haohan.cloud.scm.api.opc.req.CompleteSettlementReq;
import com.haohan.cloud.scm.api.opc.req.ReadySettlementReq;
import com.haohan.cloud.scm.api.opc.req.SettlementQueryInfoReq;
import com.haohan.cloud.scm.opc.core.impl.ScmOpcSettlementServiceImpl;
import com.pig4cloud.pigx.common.core.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;

/**
 * @author dy
 * @date 2019/7/26
 */
@RestController
@AllArgsConstructor
@RequestMapping("/api/opc/settlement")
@Api(value = "settlement", tags = "settlement管理")
public class OpcSettlementApiCtrl {

    private final ScmOpcSettlementServiceImpl scmOpcSettlementService;

    /**
     * 准备结算
     * 先判断对应的账单 其订单来源是否为确定状态(金额不会改变)
     * 确定时会创建对应结算记录(初始化,未结算)
     * 失败时不创建结算记录
     *
     * @param req 必需:pmId/settlementType/ paymentSn
     * @return 失败时返回null
     */
    @PostMapping("readySettlement")
    @ApiOperation(value = "准备结算")
    public R<SettlementRecord> readySettlement(@RequestBody @Valid ReadySettlementReq req){
        R<SettlementRecord> r = scmOpcSettlementService.readySettlement(req);
        if(null == r.getData()){
            return R.failed(r.getMsg());
        }
        return r;
    }

    /**
     * 完成结算
     *  修改对应账单状态
     * @param req
     * @return
     */
    @PostMapping("completeSettlement")
    @ApiOperation(value = "完成结算")
    public R<Boolean> completeSettlement(@RequestBody @Validated CompleteSettlementReq req){
        if(req.getSettlementAmount().compareTo(BigDecimal.ZERO) < 1){
            return R.failed("结算金额不能小于0");
        }
        R<Boolean> r = scmOpcSettlementService.completeSettlementWithPhoto(req);
        if(!r.getData()){
            return R.failed(r.getMsg());
        }
        return r;
    }

    /**
     * 结算详情
     *
     * @param req
     * @return
     */
    @GetMapping("info")
    @ApiOperation(value = "结算详情")
    public R<SettlementRecordDTO> queryInfo(@Validated SettlementQueryInfoReq req){
        SettlementRecord settlementRecord = req.transTo();
        return R.ok(scmOpcSettlementService.queryInfo(settlementRecord));
    }


}
